<template>
  <h4> 溯源管理</h4>

  <el-row>
    <el-col :span="24">
      <div style="float: left;">
        <el-button type="primary" @click="Open(null)"><el-icon>
            <Plus />
          </el-icon>&nbsp; 新增 &nbsp;</el-button>
        <el-button type="primary" @click="IsDel(null)" :disabled="!selectedRows.length"> <el-icon>
            <Delete />
          </el-icon>&nbsp; 删除 &nbsp;</el-button>
      </div>
      <div style="float: right;">
        <el-icon @click="GetProductData">
          <RefreshRight />
        </el-icon>&nbsp;
        <el-icon>
          <Setting />
        </el-icon>&nbsp;
        <el-icon @click="logic.drawer = !logic.drawer">
          <Filter />
        </el-icon>&nbsp;
      </div>
    </el-col>
  </el-row>

  <el-card v-show="logic.drawer" style="margin-top: 10px; margin-bottom: 10px;">
    <div style="padding: 10px;">
      <el-form :model="from" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="商品名称">
              <el-input v-model="from.GoodsName" placeholder="请输入商品名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产批次">
              <el-input v-model="from.ProductionBatch" placeholder="请输入生产批次"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="保质期(天)">
              <el-input v-model="from.ShelfLifeDay" placeholder="请输入保质期"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产许可证号">
              <el-input v-model="from.ProductionLicenseNumber" placeholder="请输入生产许可证号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产企业">
              <el-input v-model="from.Manufacturer" placeholder="请输入生产企业"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建人">
              <el-input v-model="from.CreateUserName" placeholder="请输入创建人"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="修改人">
              <el-input v-model="from.UpdateUserName" placeholder="请输入修改人"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间">

              <el-date-picker v-model="from.CreateTime" type="date" placeholder="请选择日期" size="size" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="text-align: right; margin-top: 10px;">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="GetProductData">查询</el-button>
      </div>
    </div>
  </el-card>

  <el-card style="margin-top: 20px;">
    <el-table :data="tableData" border style="width: 100%;height:400px;" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="55" />
      <el-table-column prop="goodsName" label="商品名称" width="150" />
      <el-table-column prop="coverImage" label="商品图片" width="60">
        <template v-slot="scoped">
          <img :src="getImageUrl(scoped.row.coverImage)" style="height: 50px;">
        </template>
      </el-table-column>
      <el-table-column prop="productionBatch" label="生产批次" width="120" />
      <el-table-column prop="shelfLifeDay" label="保质期（天）" width="120" />
      <el-table-column prop="productionLicenseNumber" label="生产许可证号" width="150" />
      <el-table-column prop="manufacturer" label="生产企业" width="200" />
      <el-table-column prop="completeness" label="信息完善度" width="120">
        <template v-slot="scoped">
          <span
            :style="{ color: Number(completenessStore.getCompleteness(scoped.row.id.toString())) >= 90 ? 'green' : 'red' }">
            {{ completenessStore.getCompleteness(scoped.row.id.toString()) }}%
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="createUserName" label="创建人" width="120" />
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template v-slot="scoped">
          {{ moment(scoped.row.createTime).format("yyyy-MM-DD HH:mm:ss") }}
        </template>
      </el-table-column>
      <el-table-column prop="updateUserName" label="修改人" width="120" />
      <el-table-column fixed="right" label="操作" min-width="220">
        <template v-slot="scoped">
          <el-button link type="primary" size="small" @click="handleClick(scoped.row.id)"
            style="color: blueviolet;">详情</el-button>
          <el-button link type="primary" size="small" @click="Open(scoped.row)">修改</el-button>
          <el-button link type="primary" size="small" @click="openExportDialog(scoped.row.id)">导出溯源码</el-button>
          <el-button link type="primary" size="small" @click="IsDel(scoped.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <div style="margin-top: 20px;float: right;">
    <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
      :page-sizes="[4, 8, 10, 20, 30, 40]" background="true" layout="total, sizes, prev, pager, next, jumper"
      :total="page.totalCount" />
  </div>


  <el-dialog v-model="logic.isOpen" align-center draggable :title="logic.Title" width="600">

    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm2" :rules="rules" label-width="auto">

      <el-form-item label="商品名称：" prop="goodsId">

        <el-select v-model="ruleForm2.goodsId" placeholder="请选择">
          <el-option v-for="item in options" :key="item.id" :label="item.goodsName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="生产批次：" prop="productionBatch">
        <el-input v-model="ruleForm2.productionBatch" />
      </el-form-item>
      <el-form-item label="保质期（天）：" prop="shelfLifeDay">
        <el-input v-model="ruleForm2.shelfLifeDay" />
      </el-form-item>
      <el-form-item label="生产许可证号：" prop="productionLicenseNumber">
        <el-input v-model="ruleForm2.productionLicenseNumber" />
      </el-form-item>
      <el-form-item label="生产企业：" prop="manufacturer">
        <el-input v-model="ruleForm2.manufacturer" />
      </el-form-item>
      <el-form-item label="封面图：" prop="coverImage">

        <el-upload class="avatar-uploader" :http-request="handleImageUpload" :show-file-list="false"
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="uploadHeaders">
          <img v-if="imageUrl.Imgs" :src="getImageUrl(imageUrl.Imgs)" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>




      </el-form-item>

      <el-form-item style="float: right;">
        <el-button @click="resetForm2(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          保存
        </el-button>
      </el-form-item>
    </el-form>

  </el-dialog>

  <!-- 添加QR码导出对话框组件 -->
  <QRCodeExportDialog v-model:visible="exportDialogVisible" :product-id="currentProductId" @export="handleExport" />

</template>
<script lang="ts" setup>
import {
  Delete,
  Menu as IconMenu,
  Plus,
  Filter,
  RefreshRight,
  Setting
} from '@element-plus/icons-vue'
import { readB, writeB, uploadB } from '@/https/http'
import { reactive, ref, watch, onMounted, onActivated } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import moment from 'moment'
import { useRouter, useRoute } from 'vue-router'
import { useCompletenessStore } from '@/stores/completeness'
import QRCodeExportDialog from '@/components/QRCodeExportDialog.vue'
import { exportQRCodes } from '@/https/qrCodeService'

const router = useRouter();
const route = useRoute();
// 使用 Pinia store 管理完善度信息
const completenessStore = useCompletenessStore();
// 获取信息完善度（保留兼容性）
const redsd = ref(completenessStore.getCurrentCompleteness);

// 从uploadB中获取API地址配置，确保一致性
// 定义统一的API地址配置，使用uploadB中的baseURL以保持一致
const API_BASE_URL = uploadB.defaults.baseURL;

// 添加上传请求头
const uploadHeaders = ref({
  Authorization: `Bearer ${window.localStorage.getItem('token')}`
})

const ruleFormRef = ref<FormInstance>()
const ruleForm2 = reactive({
  "id": 0,
  "goodsId": '',
  "productionBatch": "",
  "shelfLifeDay": '',
  "productionLicenseNumber": "",
  "manufacturer": "",
  "coverImage": ""
})


const rules = reactive<FormRules>({
  productionBatch: [
    { required: true, message: '请输入生产批次', trigger: 'blur' },
    { min: 0, max: 30, message: '字符长度【0-30】', trigger: 'blur' },
  ],
  shelfLifeDay: [
    { required: true, message: '请输入保质期', trigger: 'blur' },
    { pattern: /^\d{0,5}$/, message: '最多支持输入 5 位数字', trigger: 'blur' },

  ],
  productionLicenseNumber: [
    { required: true, message: '请输入生产许可证号', trigger: 'blur' },
    { pattern: '[a-zA-Z0-9]', message: '只允许输入数字、字母（包括大写、小写）', trigger: 'blur' },
    { min: 0, max: 30, message: '最多支持输入 30 个字符', trigger: 'blur' },
  ],
  manufacturer: [
    { required: true, message: '请输入生产批次', trigger: 'blur' },
    { pattern: '[\u4e00-\u9fa5a-zA-Z]', message: '允许输入任意字符（主要为中文、字母）不允许输入非特殊字符（如逗号、问号等）', trigger: 'blur' },
    { min: 0, max: 30, message: '最多支持输入 30 个字符', trigger: 'blur' },
  ],
  coverImage: [
    { required: true, message: '请上传图片', trigger: 'blur' },

  ],

  goodsId: [
    {
      required: true,
      message: '请选择商品',
      trigger: 'change',
    },
  ],

})



//详情方法
const handleClick = (rowId: any) => {
  //console.log('click')

  // 使用 Pinia store 保存当前查看的产品ID
  completenessStore.setCurrentProductId(rowId.toString());

  // 保存 Pinia store 数据到 sessionStorage
  completenessStore.saveToSessionStorage();

  // 跳转到详情页
  router.push({ path: "/TraceabilityEndit", query: { ProductId: rowId } })

  // 当用户从详情页返回时，会触发onActivated钩子，自动更新completeness
}







//产品信息
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')

      //判断是否是添加操作
      if (logic.value.isAdd == true) {

        writeB.post("/TraceabilityMenganment/AddProduct", ruleForm2).then(res => {

          if (res.data.code == 200) {

            ElMessage.success(res.data.message);

            logic.value.isOpen = false;//关闭弹窗
            GetProductData();

            // 初始化新产品的完善度为0
            sessionStorage.setItem("completeness", "0");

            // 跳转到详情页
            router.push({ path: "/TraceabilityEndit", query: { ProductId: res.data.data } })

          }
          else {

            ElMessage.error(res.data.message);
          }


        })



      }
      else {
        //修改产品信息操作
        writeB.post("/TraceabilityMenganment/UpdateProduct", ruleForm2).then(res => {

          if (res.data.code == 200) {

            ElMessage.success(res.data.message);

            logic.value.isOpen = false;//关闭弹窗
            GetProductData();

            // 如果当前没有完善度信息，设置一个初始值
            if (!sessionStorage.getItem("completeness")) {
              sessionStorage.setItem("completeness", "0");
            }
          }
          else {

            ElMessage.error(res.data.message);
          }

        })

      }

    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm2 = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

//商品名称下拉绑定

const options = ref([
  {
    "id": 0,
    "goodsName": ""
  },
])

//获取所有商品信息
const GetGoods = () => {

  readB.get("/TraceabilityMenganment/GetGoods").then(res => {

    if (res.data.code == 200) {

      options.value = res.data.data;

    }


  })


}

//图片上传
const imageUrl = ref({
  Imgs: ""
})

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  // 检查响应格式 (处理自定义上传和默认上传的不同响应格式)
  const responseData = response.data || response;
  const code = responseData.code || response.code;
  const data = responseData.data || response.data;

  if (code === 200 && data) {
    imageUrl.value.Imgs = data;
    ruleForm2.coverImage = data;
    console.log("上传成功，文件信息:", uploadFile);
  } else {
    console.error("上传响应格式错误:", response);
    ElMessage.error("上传失败，请检查文件格式");
  }
}

// 统一图片预览处理函数
const getImageUrl = (url: string) => {
  if (!url) return '';

  // 如果已经是完整URL，直接返回
  if (url.startsWith('http')) {
    return url;
  }

  // 确保路径以斜杠开头
  const path = url.startsWith('/') ? url : '/' + url;

  // 使用API_BASE_URL构建完整URL
  return API_BASE_URL + path;
}

// 处理图片上传 - 统一的上传函数，使用uploadB服务
const handleImageUpload = (options: any) => {
  const { file, onSuccess, onError, onProgress } = options;

  const formData = new FormData();
  formData.append('file', file);

  // 使用uploadB进行上传
  writeB.post('/TraceabilityMenganment/UpFiles', formData)
    .then(response => {
      if (response.data.code === 200) {
        onSuccess(response.data, file);
      } else {
        onError(new Error('Upload failed: ' + response.data.message));
      }
    })
    .catch(error => {
      console.error('Upload error:', error);
      onError(error);
    });
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/webp') {
    ElMessage.error('图片必须是 JPG /png/webp格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}



//条件参数
const from = ref({
  GoodsName: "",
  ProductionBatch: "",
  ShelfLifeDay: '',
  ProductionLicenseNumber: "",
  Manufacturer: "",
  CreateUserName: "",
  UpdateUserName: "",
  CreateTime: "",

})

//分页参数
const page = ref({
  PageIndex: 1,
  PageSize: 4,
  "totalCount": 0,
  "pageCount": 0,
})

//监听
watch(page.value, () => {
  GetProductData();
})


// 重置表单
const resetForm = () => {
  from.value = {
    GoodsName: "",
    ProductionBatch: "",
    ShelfLifeDay: '',
    ProductionLicenseNumber: "",
    Manufacturer: "",
    CreateUserName: "",
    UpdateUserName: "",
    CreateTime: "",
  }
}

//获取产品信息
const tableData = ref([])
//获取要删除的Ids
const selectedRows = ref([])

const GetProductData = () => {

  readB.get("/TraceabilityMenganment/GetProduct", {
    params: {
      GoodsName: from.value.GoodsName,
      ProductionBatch: from.value.ProductionBatch,
      ShelfLifeDay: from.value.ShelfLifeDay,
      ProductionLicenseNumber: from.value.ProductionLicenseNumber,
      Manufacturer: from.value.Manufacturer,
      CreateUserName: from.value.CreateUserName,
      UpdateUserName: from.value.UpdateUserName,
      CreateTime: from.value.CreateTime,
      PageIndex: page.value.PageIndex,
      PageSize: page.value.PageSize,
    }
  }).then(res => {

    if (res.data.code == 200) {
      // 设置表格数据
      tableData.value = res.data.pageData.map((item: any) => {
        // 如果 Pinia store 中没有该产品的完善度信息，为其设置一个默认值
        const productId = item.id.toString();
        if (!completenessStore.getCompleteness(productId)) {
          // 实际项目中，这里应该从后端获取真实的完善度数据
          // 这里仅用于演示，生成一个随机的完善度值
          const randomCompleteness = Math.floor(Math.random() * 100).toString();
          completenessStore.setCompleteness(productId, randomCompleteness);
        }
        return item;
      });

      // 保存 Pinia store 数据到 sessionStorage
      completenessStore.saveToSessionStorage();

      page.value.pageCount = res.data.pageCount;
      page.value.totalCount = res.data.totalCount;
    }
  })


}


//钩子函数
onMounted(() => {
  // 从 sessionStorage 加载数据到 Pinia store
  completenessStore.loadFromSessionStorage();

  // 更新本地引用
  redsd.value = completenessStore.getCurrentCompleteness;

  GetProductData();
  GetGoods();
})

// 当组件被激活时（如从其他页面返回）也刷新信息完善度数据
onActivated(() => {
  // 从 sessionStorage 加载数据到 Pinia store
  completenessStore.loadFromSessionStorage();

  // 更新本地引用
  redsd.value = completenessStore.getCurrentCompleteness;
  console.log("组件被激活，完善度:", redsd.value);

  // 刷新产品数据
  GetProductData();
})

//逻辑

const logic = ref({
  drawer: false,
  isOpen: false,
  Title: "",
  isAdd: false
})


//判断是否打开对话框
const Open = (row: any) => {

  //新增

  if (row == null) {

    logic.value.isOpen = true;
    logic.value.Title = "新增基本信息"
    logic.value.isAdd = true;
    ruleForm2.goodsId = "";
    ruleForm2.shelfLifeDay = "";
    ruleForm2.manufacturer = "";
    ruleForm2.productionBatch = "";
    ruleForm2.productionLicenseNumber = "";
    imageUrl.value.Imgs = ""

  }
  //修改
  else {
    logic.value.isOpen = true;
    logic.value.Title = "修改基本信息"
    logic.value.isAdd = false;
    ruleForm2.id = row.id;
    ruleForm2.goodsId = row.goodsId;
    ruleForm2.shelfLifeDay = row.shelfLifeDay;
    ruleForm2.manufacturer = row.manufacturer;
    ruleForm2.productionBatch = row.productionBatch;
    ruleForm2.productionLicenseNumber = row.productionLicenseNumber;
    imageUrl.value.Imgs = row.coverImage;
    ruleForm2.coverImage = row.coverImage;
    //console.log("imgs=>", ruleForm2)


  }


}


// 将选中的行数据保存到selectedRows响应式变量中,用于后续批量删除等操作
const handleSelectionChange = (val: any) => {
  selectedRows.value = val;
  //console.log("Ids=》", selectedRows.value.map((x:any) => x.id))
}



//批量逻辑删除
const IsDel = (ProductId?: any) => {
  // 单个删除产品信息
  if (ProductId != null) {
    ElMessageBox.confirm(
      '确定要删除该记录吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        writeB.post("/TraceabilityMenganment/IsDelRanger", { productIds: [ProductId] }).then(res => {
          if (res.data.code == 200) {
            ElMessage.success(res.data.message);
            GetProductData();
          } else {
            ElMessage.error(res.data.message);
          }
        })
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      })
  }
  // 批量删除操作
  else {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请先选择要删除的记录');
      return;
    }

    ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        const ids = selectedRows.value.map((x: any) => x.id);
        writeB.post("/TraceabilityMenganment/IsDelRanger", { productIds: ids }).then(res => {
          if (res.data.code == 200) {
            ElMessage.success(res.data.message);
            GetProductData();
            selectedRows.value = []; // 删除成功后清空选中的
          } else {
            ElMessage.error(res.data.message);
          }
        })
      })
      .catch(() => {
        ElMessage.info('已取消删除');
      })
  }
}

// QR码导出相关
const exportDialogVisible = ref(false)
const currentProductId = ref<string | number>('')

// 打开导出对话框
const openExportDialog = (productId: string | number) => {
  currentProductId.value = productId
  exportDialogVisible.value = true
}

// 处理导出事件
const handleExport = async (data: { productId: string | number, quantity: number }) => {
  try {
    ElMessage.info('正在生成溯源码，请稍候...')
    await exportQRCodes(data.productId, data.quantity)
    ElMessage.success(`成功导出 ${data.quantity} 个溯源码`)
  } catch (error: any) {
    console.error('导出溯源码失败:', error);
    
    // 提供更详细的错误信息
    let errorMessage = '导出失败';
    if (error.response) {
      // 服务器响应了，但状态码不是2xx
      if (error.response.status === 404) {
        errorMessage = '导出失败: API接口不存在，请联系管理员';
      } else if (error.response.status === 401) {
        errorMessage = '导出失败: 未授权，请重新登录';
      } else if (error.response.status === 400) {
        errorMessage = `导出失败: 请求参数错误 - ${error.response.data?.message || ''}`;
      } else {
        errorMessage = `导出失败: 服务器错误(${error.response.status}) - ${error.response.data?.message || ''}`;
      }
    } else if (error.request) {
      // 请求已发送但没有收到响应
      errorMessage = '导出失败: 服务器无响应，请检查网络连接';
    } else {
      // 请求设置时发生错误
      errorMessage = `导出失败: ${error.message || '未知错误'}`;
    }
    
    ElMessage.error(errorMessage);
  }
}

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
